#include "AnaDef.h"
#include "AnaAliDef.h"

void AnaRaw(TString list="list.txt", const Int_t nEvt = 1)
{
  ifstream input(list);
  if(!input){
    printf("list does not exist!\n"); exit(1);
  }

  list=list(0, list.First("."));
  TTreeSRedirector *fStream = new TTreeSRedirector(list.Append("_output.root"));

  TGrid *gr=0x0;
 
  TString buff;
  Int_t iEvent = 0; 
  Bool_t kstop = kFALSE;
  while ( input >> buff && !kstop){

    printf("opening %s\n",buff.Data());

    if(buff.Contains("alien") &&  !gr){
      gr=new TGrid;  
      gr->Connect("alien");
    }
  
    // raw reader
    AliRawReader *reader = new AliRawReaderRoot(buff); 
    reader->Reset();
    reader->Select("TRD");
    
    // TRD digit manager
    AliTRDdigitsManager manR;
    manR.CreateArrays();
    
    // loop over events
    while (reader->NextEvent() && !kstop) { 
      if(iEvent%1000==0 && iEvent){
        printf("iEvent %d\n", iEvent);
      }

      AliTRDrawStream *pstream = new AliTRDrawStream(reader);

      Short_t BCID = reader->GetBCID();

      Double_t dataVolume = 0.;
      Int_t iChamber = 0;
      while (pstream->NextChamber(&manR) >= 0) {
        
        Int_t idSM = reader->GetEquipmentId() - 1024;
        if (idSM < 0 || idSM > 17) {
          printf("strange equipment = %d\n", reader->GetEquipmentId());  
          printf("strange idSM = %d\n", idSM);
          continue;
        }

        Int_t NMCM = pstream->GetNMCMs(idSM);
        Double_t size = reader->GetDataSize() * 1e-3;//reader->GetDataSize() in byte
        
        (*fStream)<<"Chambertree"<<
          "iEvent="<<iEvent<<
          "BCID="<<BCID<<
          "iChamber="<<iChamber<<
          "idSM="<<idSM<<
          "NMCM="<<NMCM<<
          "size="<<size<<
          "\n";
        
        dataVolume += size/1e3; 
        iChamber++;

        //printf("ievent %d ichamber %d dataVolume: %f\n", iEvent, iChamber, dataVolume);
      }
      
      if(iChamber){
        //printf("dataVolume: %f\n", dataVolume);
        (*fStream)<<"Eventtree"<<
          "iEvent="<<iEvent<<
          "BCID="<<BCID<<
          "dataVolume="<<dataVolume<<
          "\n";

        iEvent++; 
        if(iEvent>=nEvt){
          kstop=kTRUE;
        }
      }
      delete pstream;   
    } // loop over events
    
    delete reader;
  } // loop over input root files


  delete fStream;

  delete gr;
}

int main(int argc, char * argv[])
{
  for(int ii=0; ii<argc; ii++){
    printf("%d: %s\n", ii, argv[ii]);
  }

  if(argc!=3){
    printf("argc!=3\n");
    return 1;
  }

  TStopwatch timer;
  timer.Start();

  AnaRaw(argv[1], atoi(argv[2]));

  timer.Stop();
  timer.Print();

  return 0;
}
